package com.mender.file.controller;

import com.mender.common.constant.MessageConstant;
import com.mender.common.result.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 文件上传
 */
@RequestMapping("/admin/common")
@RestController
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private FileStorageService fileStorageService;//注入实列
    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public Result<String> uploadFile(MultipartFile file) throws Exception
    {
        log.info("文件上传:{}",file);
        try
        {
            // 上传文件路径
//            String filePath = RuoYiConfig.getUploadPath();
//            // 上传并返回新文件名称
//            String fileName = FileUploadUtils.upload(filePath, file);
//            String url = serverConfig.getUrl() + fileName;

//            指定oss上传路径
            String format = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
//            上传图片,返回文件信息
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPath(format)
                    .upload();
            return Result.success(fileInfo == null ? MessageConstant.UPLOAD_FAILED : fileInfo.getUrl());
        }
        catch (Exception e)
        {
            log.error("文件上传失败",e);
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
